<template>
  <div class="payment-record">
    <div class="page-header">
      <h1>付款记录</h1>
      <div class="breadcrumb">财务管理 / 付款记录</div>
    </div>

    <div class="search-section">
      <div class="search-form">
        <div class="form-item">
          <label>付款编号</label>
          <input v-model="searchForm.paymentCode" type="text" placeholder="请输入付款编号" />
        </div>
        <div class="form-item">
          <label>供应商</label>
          <input v-model="searchForm.supplier" type="text" placeholder="请输入供应商名称" />
        </div>
        <div class="form-item">
          <label>付款日期</label>
          <input v-model="searchForm.paymentDate" type="date" />
        </div>
        <div class="form-buttons">
          <button class="btn btn-primary" @click="searchRecords">查询</button>
          <button class="btn btn-secondary" @click="resetSearch">重置</button>
        </div>
      </div>
    </div>

    <div class="table-pagination-section">
      <div class="table-container">
        <table class="data-table">
          <thead>
            <tr>
              <th>付款编号</th>
              <th>供应商</th>
              <th>付款金额</th>
              <th>付款方式</th>
              <th>付款日期</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="record in recordList" :key="record.id">
              <td>{{ record.paymentCode }}</td>
              <td>{{ record.supplierName }}</td>
              <td>{{ record.amount }}元</td>
              <td>{{ record.method }}</td>
              <td>{{ record.paymentDate }}</td>
              <td>
                <button class="btn btn-small btn-primary" @click="viewDetail(record)">
                  <span class="btn-icon">🔍</span>
                  查看
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <div class="pagination">
        <div class="pagination-info">共{{ totalPages }}页/{{ totalItems }}条数据</div>
        <div class="pagination-controls">
          <button class="btn btn-page" :disabled="currentPage === 1" @click="changePage(currentPage - 1)">上一页</button>
          <button v-for="page in visiblePages" :key="page" class="btn btn-page" :class="{ active: page === currentPage }" @click="changePage(page)">{{ page }}</button>
          <button class="btn btn-page" :disabled="currentPage === totalPages" @click="changePage(currentPage + 1)">下一页</button>
        </div>
      </div>
    </div>

    <!-- 付款详情模态框 -->
    <div v-if="showDetailModal" class="modal-overlay" @click="showDetailModal = false">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>付款详情</h3>
          <button class="modal-close" @click="showDetailModal = false">&times;</button>
        </div>
        <div class="modal-body">
          <div class="detail-grid">
            <div class="detail-item">
              <label>付款编号：</label>
              <span>{{ selectedRecord?.paymentCode }}</span>
            </div>
            <div class="detail-item">
              <label>供应商：</label>
              <span>{{ selectedRecord?.supplierName }}</span>
            </div>
            <div class="detail-item">
              <label>付款金额：</label>
              <span class="highlight-amount">{{ selectedRecord?.amount }}元</span>
            </div>
            <div class="detail-item">
              <label>付款方式：</label>
              <span>{{ selectedRecord?.method }}</span>
            </div>
            <div class="detail-item">
              <label>付款日期：</label>
              <span>{{ selectedRecord?.paymentDate }}</span>
            </div>
            <div class="detail-item">
              <label>创建人：</label>
              <span>{{ selectedRecord?.creator }}</span>
            </div>
            <div class="detail-item">
              <label>创建时间：</label>
              <span>{{ selectedRecord?.createTime }}</span>
            </div>
            <div class="detail-item">
              <label>记录类型：</label>
              <span>{{ selectedRecord?.recordType || '手动付款' }}</span>
            </div>
            <div class="detail-item full-width">
              <label>备注：</label>
              <span>{{ selectedRecord?.remark || '-' }}</span>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="showDetailModal = false">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { apiGet, apiPost } from '../../utils/api.js'

const searchForm = reactive({
  paymentCode: '',
  supplier: '',
  paymentDate: ''
})

const recordList = ref([])
const currentPage = ref(1)
const totalPages = ref(5)
const totalItems = ref(50)
const showDetailModal = ref(false)
const selectedRecord = ref(null)

const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, currentPage.value + 2)
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  return pages
})

const searchRecords = async () => {
  currentPage.value = 1
  await loadRecordData()
}

const resetSearch = async () => {
  searchForm.paymentCode = ''
  searchForm.supplier = ''
  searchForm.paymentDate = ''
  currentPage.value = 1
  await loadRecordData()
}

const changePage = async (page) => {
  currentPage.value = page
  await loadRecordData()
}

const viewDetail = (record) => {
  selectedRecord.value = record
  showDetailModal.value = true
}

const loadRecordData = async () => {
  try {
    // 构建查询参数
    const params = new URLSearchParams({
      page: currentPage.value,
      size: 10,
      ...(searchForm.paymentCode && { paymentCode: searchForm.paymentCode }),
      ...(searchForm.supplier && { supplier: searchForm.supplier }),
      ...(searchForm.paymentDate && { paymentDate: searchForm.paymentDate })
    })

    // 获取手动付款记录（已完成的）
    const manualPayments = await apiGet(`/finance/manual-payments?${params}`)

    // 获取已审批通过的付款记录
    const approvedPayments = await apiGet(`/finance/payment-approvals?${params}&status=approved`)

    // 获取已审批通过的订单付款记录（新的业务逻辑）
    const orderPayments = await apiGet(`/finance/order-payments?${params}`)

    // 调试信息

    
    // 检查数据完整性


    // 合并所有付款记录
    let allRecords = []

    // 处理手动付款记录
    if (manualPayments.content) {
      manualPayments.content.forEach(payment => {
        allRecords.push({
          id: `manual_${payment.id}`,
          paymentCode: payment.paymentCode || `MP${String(payment.id).padStart(8, '0')}`,
          supplierName: payment.supplierName || '未知供应商',
          amount: payment.paymentAmount,
          method: payment.paymentMethod,
          paymentDate: payment.paymentDate,
          remark: payment.remark,
          creator: payment.creator,
          createTime: payment.createTime,
          recordType: '手动付款'
        })
      })
    }

    // 处理已审批的付款记录
    if (approvedPayments.content) {
      approvedPayments.content.forEach(payment => {
        allRecords.push({
          id: `approved_${payment.id}`,
          paymentCode: payment.paymentCode || `AP${String(payment.id).padStart(8, '0')}`,
          supplierName: payment.supplierCustomer || '未知供应商',
          amount: payment.applicationAmount,
          method: payment.paymentMethod,
          paymentDate: payment.applicationDate,
          remark: payment.remark,
          creator: payment.applicant,
          createTime: payment.applicantTime,
          recordType: '审批付款'
        })
      })
    }

    // 处理已审批通过的订单付款记录（只显示已付款的订单）
    if (orderPayments.content) {
      orderPayments.content.forEach(payment => {
        // 只显示已审批通过的订单付款记录
        if (payment.applicationStatus === 3 || payment.applicationStatus === 4) { // 已审批或已付款
          allRecords.push({
            id: `order_${payment.id}`,
            paymentCode: payment.orderNumber || `OP${String(payment.id).padStart(8, '0')}`,
            supplierName: payment.supplierCustomerName || '未知供应商',
            amount: payment.applicationAmount || payment.paidAmount, // 使用申请金额或已付金额
            method: payment.paymentMethod || '订单付款',
            paymentDate: payment.paymentDate || payment.applicationTime,
            remark: payment.remark,
            creator: payment.applicant || payment.creatorName,
            createTime: payment.applicationTime || payment.createTime,
            recordType: '订单付款'
          })
        }
      })
    }

    // 前端过滤（如果后端搜索无效）
    if (searchForm.paymentCode && searchForm.paymentCode.trim()) {
      allRecords = allRecords.filter(record => 
        record.paymentCode && record.paymentCode.toLowerCase().includes(searchForm.paymentCode.toLowerCase())
      )
    }
    
    if (searchForm.supplier && searchForm.supplier.trim()) {
      allRecords = allRecords.filter(record => 
        record.supplierName && record.supplierName.toLowerCase().includes(searchForm.supplier.toLowerCase())
      )
    }
    
    if (searchForm.paymentDate && searchForm.paymentDate.trim()) {
      allRecords = allRecords.filter(record => 
        record.paymentDate && record.paymentDate.includes(searchForm.paymentDate)
      )
    }

    // 数据验证和清理
    allRecords.forEach(record => {
      // 确保所有必要字段都有值
      if (!record.paymentCode || record.paymentCode.trim() === '') {
        record.paymentCode = `UNK${String(record.id).padStart(8, '0')}`
      }
      if (!record.supplierName || record.supplierName.trim() === '') {
        record.supplierName = '未知供应商'
      }
      if (!record.amount || record.amount === 0) {
        record.amount = '0.00'
      }
      if (!record.method || record.method.trim() === '') {
        record.method = '未知方式'
      }
      if (!record.paymentDate) {
        record.paymentDate = record.createTime || new Date().toISOString().split('T')[0]
      }
    })
    
    // 按创建时间排序（最新的在前）
    allRecords.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))

    // 分页处理
    const startIndex = (currentPage.value - 1) * 10
    const endIndex = startIndex + 10
    recordList.value = allRecords.slice(startIndex, endIndex)

    totalItems.value = allRecords.length
    totalPages.value = Math.ceil(allRecords.length / 10)
    
    // 最终数据验证日志


  } catch (error) {
    console.error('加载付款记录失败:', error)
    // 使用模拟数据作为后备
    recordList.value = Array.from({ length: 10 }, (_, index) => ({
      id: index + 1,
      paymentCode: `FK${String(index + 1).padStart(4, '0')}`,
      supplierName: 'XXX有限公司',
      amount: '5000.00',
      method: '银行转账',
      paymentDate: '2024-08-26',
      remark: '',
      creator: '夏油杰',
      createTime: '2024-08-26',
      recordType: '手动付款'
    }))
    totalItems.value = 50
    totalPages.value = 5
  }
}

onMounted(async () => {
  await loadRecordData()
})
</script>

<style scoped>
.payment-record {
  padding: 20px;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  position: relative;
}

.payment-record::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="75" cy="75" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="50" cy="10" r="0.5" fill="rgba(255,255,255,0.1)"/><circle cx="10" cy="60" r="0.5" fill="rgba(255,255,255,0.1)"/><circle cx="90" cy="40" r="0.5" fill="rgba(255,255,255,0.1)"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
  opacity: 0.3;
  pointer-events: none;
}

.page-header {
  margin-bottom: 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 25px 30px;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
  position: relative;
  overflow: hidden;
}

.page-header::before {
  content: '';
  position: absolute;
  top: -50%;
  right: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
  animation: float 6s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translateY(0px) rotate(0deg); }
  50% { transform: translateY(-20px) rotate(180deg); }
}

.page-header h1 {
  margin: 0 0 10px 0;
  font-size: 32px;
  color: white;
  font-weight: 700;
  text-shadow: 0 2px 4px rgba(0,0,0,0.3);
  position: relative;
  z-index: 1;
}

.breadcrumb {
  color: rgba(255, 255, 255, 0.9);
  font-size: 16px;
  font-weight: 500;
  position: relative;
  z-index: 1;
}

.search-section {
  background: rgba(255, 255, 255, 0.95);
  padding: 25px 30px;
  border-radius: 16px;
  margin-bottom: 25px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  position: relative;
  overflow: hidden;
}

.search-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
}

.search-form {
  display: flex;
  gap: 20px;
  align-items: flex-end;
  flex-wrap: wrap;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-item label {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.form-item input,
.form-item select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  min-width: 150px;
}

.form-buttons {
  display: flex;
  gap: 10px;
}

.table-pagination-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  position: relative;
  overflow: hidden;
  margin-bottom: 25px;
}

.table-pagination-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, #4facfe 0%, #00f2fe 50%, #43e97b 100%);
}

.table-container {
  overflow-x: auto;
  padding: 20px 20px 0 20px;
  background: transparent;
  border-radius: 0;
  box-shadow: none;
  border: none;
  backdrop-filter: none;
  position: static;
  overflow: visible;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.data-table th,
.data-table td {
  padding: 12px 8px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.data-table th {
  background: #f8f9fa;
  font-weight: 600;
  color: #495057;
  padding: 16px 12px;
  border: none;
  position: relative;
  border-bottom: 2px solid #e9ecef;
}

.data-table tbody tr {
  transition: all 0.3s ease;
  border-bottom: 1px solid rgba(225, 229, 233, 0.5);
}

.data-table tbody tr:hover {
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.data-table tbody tr:last-child {
  border-bottom: none;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 20px 20px;
  background: transparent;
  border-radius: 0;
  box-shadow: none;
  border: none;
  backdrop-filter: none;
  position: static;
  overflow: visible;
  border-top: 1px solid #e9ecef;
}

.pagination-info {
  color: #666;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  gap: 5px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 12px;
  font-weight: 600;
  transition: all 0.3s ease;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  color: white !important;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4) !important;
}

.btn-primary:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
}

.btn-primary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.btn-secondary {
  background: linear-gradient(135deg, #6c757d 0%, #495057 100%) !important;
  color: white !important;
  box-shadow: 0 4px 15px rgba(108, 117, 125, 0.4) !important;
}

.btn-secondary:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(108, 117, 125, 0.6);
}

.btn-small {
  padding: 6px 12px;
  font-size: 12px;
  margin-right: 5px;
  min-width: 60px;
}

.btn-page {
  background: rgba(255, 255, 255, 0.9);
  color: #333;
  border: 2px solid #e1e5e9;
  border-radius: 12px;
  padding: 10px 16px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.btn-page:hover {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-color: transparent;
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
}

.btn-page.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-color: transparent;
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.4);
}

.btn-page:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow: hidden;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  border: 1px solid #e1e5e9;
  position: relative;
}

.modal-header {
  padding: 18px 20px 16px 20px;
  border-bottom: 1px solid #e1e5e9;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  color: white !important;
  border-radius: 12px 12px 0 0;
}

.modal-header h3 {
  margin: 0;
  color: white;
  font-size: 16px;
  font-weight: 600;
}

.modal-close {
  background: rgba(255, 255, 255, 0.2) !important;
  border: none !important;
  font-size: 16px !important;
  cursor: pointer !important;
  color: white !important;
  width: 24px !important;
  height: 24px !important;
  border-radius: 50% !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  transition: all 0.2s !important;
}

.modal-close:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.1);
}

.modal-body {
  padding: 16px 20px;
  max-height: calc(80vh - 120px);
  overflow-y: auto;
  overflow-x: hidden;
  width: 100%;
  box-sizing: border-box;
}

.modal-footer {
  padding: 14px 20px 18px 20px;
  border-top: 1px solid #e1e5e9;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  background: #f8f9fa;
  border-radius: 0 0 12px 12px;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  margin-top: 0;
  margin-bottom: 20px;
  font-size: 18px;
  color: #2c3e50;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.detail-section h4::before {
  content: '';
  width: 4px;
  height: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  margin-right: 12px;
  border-radius: 2px;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
}

.detail-item {
  display: flex;
  align-items: center;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #667eea;
}

.detail-item.full-width {
  grid-column: 1 / -1;
}

.detail-item label {
  font-weight: 500;
  color: #495057;
  margin-right: 12px;
  min-width: 100px;
}

.detail-item span {
  font-weight: 600;
  color: #2c3e50;
}

.highlight-amount {
  color: #e74c3c;
  font-weight: 700;
  font-size: 16px;
}

/* 按钮样式优化 */
.btn {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s ease;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.btn-primary:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
}

.btn-primary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.btn-secondary {
  background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
  color: white;
  box-shadow: 0 4px 15px rgba(108, 117, 125, 0.4);
}

.btn-secondary:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(108, 117, 125, 0.6);
}

.btn-small {
  padding: 8px 16px;
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .detail-grid {
    grid-template-columns: 1fr;
  }

  .modal-content {
    width: 95%;
    margin: 20px;
  }

  .modal-body {
    padding: 16px;
  }

  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>


